<template>
  <layout title="补贴名单与公示批次列表">
    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        mode="search"
        v-model="tableSearch"
        layout="inline"
        :FormList="searchColumns"
      >
        <a-button
          class="action-button"
          type="primary"
          icon="search"
          @click="search()"
        >搜索</a-button>

        <!-- 标准流程 -->
        <template v-if="!isPlant">
          <a-button
            class="action-button"
            type="default"
            :auth="{
              keys: ['publish.add', !(currentAreaId.length < (isLarge ? 6 : 12))],
              relate: 'and'
            }"
            @click="handlerPublic()"
          >起草公示信息</a-button>
        </template>

        <!-- 一次性补贴 -->
        <template v-else>
          <a-button
            class="action-button"
            type="default"
            :auth="{
              keys: ['publish.add', !(currentAreaId.length < 12)],
              relate: 'and'
            }"
            showDefaultLabel
            @click="handlerPublic()"
          >起草农户公示</a-button>
          <a-button
            class="action-button"
            type="default"
            :auth="{
              keys: ['publish.add', !(currentAreaId.length < 6)],
              relate: 'and'
            }"
            showDefaultLabel
            @click="handlerPublic(true)"
          >起草大户公示</a-button>
        </template>
        
        <a-button
          class="action-button"
          type="default"
          auth="publish.export-member-list"
          @click="handlerExportMembers()"
        >按辖区导出公示信息</a-button>

        <a-popconfirm
          title="您确认批量撤销下列公示?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handlerRevokePublic()"
        >
          <a-button
            type="default"
            :auth="{
              keys: ['publish.revoke-public', !(currentAreaId.length <= 6)],
              relate: 'and'
            }"
          >批量撤销下列公示</a-button>
        </a-popconfirm>

        <span>{{readme}}</span>
      </custom-form>
      <!-- <a-input placeholder="产品名称或者编号" v-model="tableSearch.searchKey" allowClear style="width: 200px;" /> -->
    </section>

    <a-alert :message="`应补贴：${countData.bt_size}亩 / ${countData.bt_member}户，已公示：${countData.pub_size}亩 / ${countData.pub_member}户，公示记录：${total}条`"></a-alert>
    <br>

    <!-- 产品列表 -->
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="record => record.pub_id"
      :customRow="customTableRow"
      :pagination="false"
      :loading="tableLoading"
      :scroll="{
        x: '100%',
        y: tableClientHeight + 100
      }"
      bordered
    >
      <template
        slot="pub_id"
        slot-scope="row"
      >
        <a-button type="link" @click="handlerPublishMember(row)">{{row.pub_id}}</a-button>
      </template>
      <template
        slot="pub_state"
        slot-scope="row"
      >
        <span color="pink" v-if="getCurrentPubStatus(row)">{{getCurrentPubStatus(row)}}</span>
      </template>

      <template
        slot="start_time"
        slot-scope="row"
      >
        {{getCurrentTimeArea(row).startTime}}
      </template>

      <template
        slot="end_time"
        slot-scope="row"
      >
        {{getCurrentTimeArea(row).endTime}}
      </template>
      <!-- 按钮区 -->
      <template
        slot="action"
        slot-scope="row, record, index"
      >
        <template v-if="index !== 0 && row.pub_ck_state1 !== publishStatusEnum.PUBLIC_WAIT">
          <a-button
            class="action-button"
            type="link"
            size="small"
            v-if="tableSearch.pub_state !== '2'"
            auth="publish.member-list"
            @click="handlerPublishMember(row)"
          >详细</a-button>
          <a-popconfirm
            title="您确认当前直接选择撤销公示?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="handlerChangeState(row, publishStatusEnum.PUBLIC_CANCEL, false)"
          >
            <a-button
              class="action-button"
              type="link"
              size="small"
              auth="publish.reject"
            >撤销公示</a-button>
          </a-popconfirm>

          <!-- <a-popconfirm
            title="您确认当前直接选择第一次公示通过?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="handlerChangeState(row, publishStatusEnum.PUBLIC_SUCCESS, 1)"
          >
            <a-button
              class="action-button"
              type="link"
              size="small"
              :auth="{
                keys: ['publish.first-pass', row.pub_ck_state1 !== publishStatusEnum.PUBLIC_SUCCESS],
                relate: 'and'
              }"
            >1次通过</a-button>
          </a-popconfirm>

          <a-popconfirm
            title="您确认当前直接选择第二次公示通过?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="handlerChangeState(row, publishStatusEnum.PUBLIC_SUCCESS, 2)"
          >
            <a-button
              class="action-button"
              type="link"
              size="small"
              :auth="{
                keys: ['publish.second-pass', row.pub_ck_state1 === publishStatusEnum.PUBLIC_SUCCESS, row.pub_ck_state2 !== publishStatusEnum.PUBLIC_SUCCESS ,hasNext(9)],
                relate: 'and'
              }"
            >2次通过</a-button> -->
          </a-popconfirm>
          
        </template>
        <!-- <a-popconfirm
          title="您确认导出该公示下人员信息?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handlerExportPublishMemberExecl(row)"
        >
          <a-button
            class="action-button"
            type="link"
            size="small"
            auth="publish.export-member-list"
          >导出公示人员</a-button>
        </a-popconfirm> -->
        
        
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      showSizeChanger
      :pageSize="pageSize"
      :show-total="showTotal"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      centered
      @cancel="visible = false"
      @ok="handleSubmit"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="formMode"
        v-bind="formItemLayout"
        layout="horizontal"
      ></custom-form>
    </a-modal>

    <!-- <a-drawer
      :title="'公示标题：' + currentRow.pub_title"
      placement="right"
      :closable="false"
      width="80%"
      :visible="drawerVisible"
      @close="drawerVisible = false"
    >
      <MemberLargeGrain
        :currentPublishId="currentRow.pub_id"
        ref="MemberLargeGrain"
        v-if="isLarge"
      />
      <MemberGrain
        :currentPublishId="currentRow.pub_id"
        ref="MemberGrain"
        v-else
      />
    </a-drawer> -->

  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { publishServices, IPublish } from '@/common/services/publish'
import { publishStatus, publishStatusMap, publishStatusEnum } from '@/common/enum'
import { userModule } from '@/store/modules/user'
import MemberGrain from '../../member/grain/Grain.vue'
import MemberLargeGrain from '../../member/large-grain/Grain.vue'
import PublicMemberList from './PublicMemberList.vue'
import PublicDetail from './PublicDetail.vue'
import PublicSelectExport from './PublicSelectExport.vue'
import { message } from 'ant-design-vue'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
    MemberGrain,
    MemberLargeGrain,
    PublicMemberList,
    PublicDetail,
    PublicSelectExport
  }
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  @Prop({
    type: String
  })
  public currentAreaId!: string

  get isLarge() {
    return userModule.isLarge
  }

  get isPlant() {
    return userModule.isPlant
  }

  get currentProject () {
    return userModule.currentProject
  }

  public commonParams = {
    s_a_id: ''
  }

  public hasTotalRow = true

  // 产品列表搜索条件
  public tableSearch = {
    pub_state: '',
    show_area: '0'
  }

  public readme = ''
  public countData: Record<string, number> = {
    bt_member: 0,
    bt_size: 0,
    pub_size: 0,
    pub_member: 0
  }

  // 自定义mode
  public customMode = 'add'

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    {
      title: '公示编号',
      key: 'pub_id',
      scopedSlots: { customRender: 'pub_id' },
      width: 120,
      form: {
        type: 'a-input',
        placeholder: '编号自动生成',
        disabled: true
      }
    },
    {
      title: '查询范围',
      key: 'show_area',
      dataIndex: 'show_area',
      width: 80,
      form: {
        type: 'a-radio-group',
        placeholder: '请选择大户类型',
        dict: [
          {
            label: '本区域申报的',
            value: '0'
          },
          {
            label: '本区域种植的',
            value: '1'
          }
        ],
        isShowQuery: this.isLarge,
        isShowAll: false,
        isShowList: false,
        renderMode: ['search']
      }
    },
    {
      title: '公示对象所属行政区',
      dataIndex: 's_a_nam_all',
      key: 's_a_nam_all',
      width: 300
    },

    {
      title: '应补贴(户)',
      dataIndex: 'bt_member_num',
      key: 'bt_member_num',
      align: 'right',
      width: 100
    },

    {
      title: '应补贴(亩)',
      dataIndex: 'bt_size',
      key: 'bt_size',
      align: 'right',
      width: 140
    },

    {
      title: '公示(户)',
      dataIndex: 'pub_member_num',
      key: 'pub_member_num',
      align: 'right',
      width: 100
    },

    {
      title: '公示面积(亩)',
      dataIndex: 'pub_bt_size',
      key: 'pub_bt_size',
      align: 'right',
      width: 130
    },

    {
      title: '补贴标准',
      dataIndex: 'pay_price',
      key: 'pay_price',
      align: 'right',
      width: 130
    },

    // {
    //   title: '公示状态',
    //   scopedSlots: { customRender: 'pub_state' },
    //   key: 'pub_state',
    //   width: 130,
    //   form: {
    //     type: 'a-select',
    //     placeholder: '',
    //     renderMode: ['edit'],
    //     dict: publishStatus.filter(item => item.value !== publishStatusEnum.PUBLIC_CANCEL),
    //     isShowQuery: true,
    //     handler: {
    //       change: () => {
    //         this.getData()
    //       }
    //     }
    //   }
    // },
    {
      title: '最初公示时间',
      key: 'start_time',
      width: 150,
      scopedSlots: { customRender: 'start_time' }
    },
    {
      title: '最后公示时间',
      key: 'end_time',
      width: 150,
      scopedSlots: { customRender: 'end_time' }
    },
    // {
    //   title: '备注',
    //   dataIndex: 'readme',
    //   key: 'readme',
    //   form: {
    //     type: 'a-textarea',
    //     placeholder: ''
    //   },
    //   width: 200
    // },

    {
      title: '操作',
      key: 'action',
      width: 160,
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]

  public tableApi = {
    list: publishServices.getPublishList,
    add: publishServices.updatePublish,
    edit: publishServices.updatePublish
    // del: userServices.deleteAdmin,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    this.getData()
  }

  get publishStatusEnum() {
    return publishStatusEnum
  }

  get currentUserArea() {
    return userModule.currentUserArea
  }

  public mounted() {
  }

  public hasReject(row: IPublish) {

    // 任意一次包含未通过
    const isFail = [
      row.pub_ck_state3,
      row.pub_ck_state2,
      row.pub_ck_state1,
    ].includes(publishStatusEnum.PUBLIC_CANCEL)

    // 全部已通过
    const isAllSuccess = [
      row.pub_ck_state3,
      row.pub_ck_state2,
      row.pub_ck_state1,
    ].every(_ => _ === publishStatusEnum.PUBLIC_SUCCESS)

    return isFail || (isAllSuccess && this.currentUserArea.s_a_id.length > 6)
  }

  public hasNext(scalc: number) {
    // length 村，社 14/12；乡镇 9； 区县 6
    return this.currentUserArea.s_a_id.length <= scalc
  }

  public async getData() {
    const res = await this.getTableList()
    this.readme = res.data.readme || ''
    this.countData.bt_member = res.data.bt_member || 0
    this.countData.bt_size = res.data.bt_size || 0
    this.countData.pub_size = res.data.pub_size || 0
    this.countData.pub_member = res.data.pub_member || 0
  }

  public handlerTableAdd() {
    this.tableAdd()
    this.$nextTick(() => {
      this.currentRow = Object.assign(
        {},
        { s_a_id: this.currentAreaId, pub_state: '1' }
      )
    })
  }

  // 获取当前公示状态
  public getCurrentPubStatus(row: IPublish) {
    const array = [
      // row.pub_ck_state3,
      row.pub_ck_state2,
      row.pub_ck_state1
    ]

    const rejectIndex = array.indexOf(publishStatusEnum.PUBLIC_CANCEL)

    // 有公示不通过情况
    if (rejectIndex !== -1) {
      const texts = [
        // "三",
        "二",
        "一"
      ]
      return `第${texts[rejectIndex]}次` + publishStatusMap.get(array[rejectIndex])
    }

    if (row.pub_ck_state1 === '0' || row.pub_ck_state2 === '0') {
      return "公示中"
    }

    // 三级公示
    // if (+row.pub_ck_state3) {
    //   return "第三次" + publishStatusMap.get(row.pub_ck_state3)
    // }
    // 二级公示
    if (+row.pub_ck_state2 || +row.pub_ck_state2 === 0) {
      return "第二次" + publishStatusMap.get(row.pub_ck_state2)
    }
    // 一级公示
    if (+row.pub_ck_state1 || +row.pub_ck_state1 === 0) {
      return "第一次" +  publishStatusMap.get(row.pub_ck_state1)
    }
  }

  // 获取最初和最后公示时间
  public getCurrentTimeArea(row: IPublish) {
    return {
      startTime: row.pub_ck_start1 || row.pub_ck_start2 || row.pub_ck_start3,
      endTime: row.pub_ck_end3 || row.pub_ck_end2 || row.pub_ck_end1
    }
  }

  // 起草公示
  public handlerPublic(isLargeMember: boolean = false) {
    this.$dialog(PublicMemberList, {
      currentAreaId: this.currentAreaId,
      isPreview: true,
      isLargeMember
    }, {
      title: '待起草公示人员预览表',
      width: '80%',
      centered: true,
      maskClosable: false,
      okText: '确认发布',
      cancelText: '放弃',
      on: {
        ok: async () => {
          await publishServices.updatePublish({
            s_a_id: this.currentAreaId,
            is_big_member: isLargeMember
          })
          this.$message.success('起草公示成功')
          this.getData()
          return true;
        }
      }
    })
  }

  // 撤销公示
  public handlerRevokePublic() {
    const hideMessage = message.loading('撤销中...', 0)
    publishServices.revokePublic({
      s_a_id: this.currentAreaId
    }).then(_ => {
      this.$message.success('撤销成功')
      this.getData()
    }).finally(() => {
      hideMessage()
    })
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: IPublish) {
    this.tableEdit(Object.assign({}, row))
  }

  // 公示人员
  public handlerPublishMember(row: IPublish) {
    this.$dialog(PublicDetail, {
      currentPub: row,
      currentPubId: row.pub_id,
      currentAreaId: row.s_a_id,
      showArea: this.tableSearch.show_area
    }, {
      title: this.currentProject.task_nam +'公示',
      width: '90%',
      bodyStyle: {
        maxHeight: '80vh',
        overflowY: 'scroll'
      },
      centered: true,
      maskClosable: false,
      footer: null,
      cancel: () => {
        this.getData()
      }
    })
  }

  // 导出
  public handlerExportPublishMemberExecl(row: IPublish) {
    // publishServices.exportPublishMemberExecl({
    //   pub_id: row.pub_id
    // }).then(_ => {
    //   // 获取execl-key
    //   const fields: Record<string, string> = this.isLarge ? {
    //     "big_mb_id": "大户编号",
    //     "big_mb_nam": "大户名称",
    //     "big_mb_type_nam": "大户类型",
    //     "big_mb_law_id": "法定编码",
    //     "big_mb_addr": "注册地址",
    //     "big_mb_bank_id": "银行卡号",
    //     "big_mb_band_user": "开户名",
    //     "big_mb_bank_code": "开户行",
    //     "big_mb_user": "法人",
    //     "big_mb_contact": "联系人",
    //     "big_mb_tel": "联系电话",
    //     "field": "耕地总面积",
    //     "field_had": "承包确权面积(亩)",
    //     "field_gave": "租用确权面积(亩)",
    //     "plant": "粮食种植面积(亩)",
    //     "material": "购买农资花费(元)",
    //     "machine": "农机数量(台)",
    //     // "big_mb_ck1": "乡镇审核意见",
    //     // "big_mb_ck_u1": "乡镇审核人姓名",
    //     // "big_mb_time1": "乡镇审核时间",
    //     // "big_mb_ck2": "村委审核意见",
    //     // "big_mb_ck_u2": "村委审核人姓名",
    //     // "big_mb_time2": "村委审核时间",
    //     // "big_mb_ck3": "驻村干部审核意见",
    //     // "big_mb_ck_u3": "驻村干部审核人姓名",
    //     // "big_mb_time3": "驻村干部审核时间",
    //     "pay_price": "每亩补贴金额",
    //     "pay_unit": "补贴参照",
    //     "pay_total": "补贴总金额"
    //   } : {
    //     "member_id": "农户编号",
    //     "member_nam": "户主姓名",
    //     "member_addr": "家庭住址",
    //     "field": "耕地总面积",
    //     "field1": "承包确权面积",
    //     "field2": "租用确权面积",
    //     "plant": "粮食种植面积",
    //     "pay_price": "每亩补贴金额",
    //     "pay_unit": "补贴参照",
    //     "pay_total": "补贴总金额"
    //   }
    //   exportDataHandler(_.data, fields, row.pub_id + row.pub_title + '.xlsx')
    //   this.$message.success('导出成功')
    // })
  }

  public handlerChangeState(row: IPublish, state: publishStatusEnum, step: boolean | number) {
    let params: Partial<IPublish> = {}
    // 公示通过
    if (step === false) {
      params.pub_ck_state1 = state;
      params.pub_ck_state2 = state;
    } else if (step === 1) {
      params.pub_ck_state1 = state
    } else if (step === 2) {
      params.pub_ck_state2 = state
    }
    this.tableLoading = true
    publishServices.updatePublish({
      pub_id: row.pub_id,
      s_a_id: row.s_a_id,
      ...params
    }).then(() => {
      this.$message.success('更新成功')
      this.getData();
    }).finally(() => {
      this.tableLoading = false
    })
  }

  public handlerExportMembers() {
    const currentAreaId = this.currentAreaId
    this.$dialog(PublicSelectExport, {
    }, {
      title: '请选择导出字段',
      width: '600px',
      bodyStyle: {
        maxHeight: '80vh',
      },
      centered: true,
      maskClosable: false,
      on: {
        async ok() {
          // @ts-ignore
          const fields = this.$refs._component.currentSelected
          // @ts-ignore
          const type = this.$refs._component.currentType as string
          if (!fields.length) {
            message.error("请选择导出字段")
            return false
          }
          const loading = message.loading('导出中。。。', 0)
          const _ = await publishServices.exportPublishMemberExecl({
            export_area: currentAreaId,
            exportExcelMode: type,
            keys: fields
          })
          loading()

          // 异常信息
          if (_.data.type === 'application/json') {
            const reader = new FileReader();
            reader.readAsText(_.data);
            reader.onload = () => {
              const data = JSON.parse(reader.result as string)
              message.error(data.msg);
            }
          } else {
            // @ts-ignore
            const filename = _.headers['content-disposition'].replace(/(.*)(?=filename=)/g, '').replace('filename=', '');
            const data = _.data
            const url = window.URL.createObjectURL(data)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', decodeURI(filename))
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
          
          return true
        }
      }
    })
    
  }
}
</script>

<style scoped lang="less">
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}
</style>
